package com.mu.manger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mu.domain.MessageEntity;
import com.mu.domain.RoleContent;
import lombok.extern.slf4j.Slf4j;
import okhttp3.WebSocket;
import org.springframework.beans.factory.annotation.Value;

import java.util.List;
import java.util.UUID;

/**
 * @author shang
 */
@Slf4j
public class MessageThread extends Thread {

    public String appid;

    private WebSocket webSocket;
    private String userId;
    private String sendMsg;
    private boolean wsCloseFlag;

    public MessageThread(WebSocket webSocket, String userId, String sendMsg, String appid) {
        this.webSocket = webSocket;
        this.userId = userId;
        this.sendMsg = sendMsg;
        this.appid = appid;
    }

    @Override
    public void run() {
        try {
            JSONObject requestJson=new JSONObject();

            // header参数
            JSONObject header=new JSONObject();
            header.put("app_id",appid);
            header.put("uid", userId);

            // parameter参数
            JSONObject parameter=new JSONObject();
            JSONObject chat=new JSONObject();
            chat.put("domain","generalv2");
            chat.put("temperature",0.5);
            chat.put("max_tokens",4096);
            parameter.put("chat",chat);

            // payload参数
            JSONObject payload=new JSONObject();
            JSONObject message=new JSONObject();
            JSONArray text=new JSONArray();
            MessageEntity messageEntity = MessageEntity.getSingleton();
            MessageCallBack messageCallBack = MessageCallBack.getSingleton();
            List<RoleContent> historyList = messageEntity.getHistoryList();
            // 历史问题获取
            if(!historyList.isEmpty()){
                for(RoleContent tempRoleContent : historyList){
                    text.add(JSON.toJSON(tempRoleContent));
                }
            }

            // 最新问题
            RoleContent roleContent = new RoleContent();
            roleContent.setRole("user");
            roleContent.setContent(sendMsg);
            text.add(JSON.toJSON(roleContent));
            historyList.add(roleContent);


            message.put("text",text);
            payload.put("message",message);


            requestJson.put("header",header);
            requestJson.put("parameter",parameter);
            requestJson.put("payload",payload);
            // 可以打印看每次的传参明细
            webSocket.send(requestJson.toString());
            messageEntity.setWebsocket(userId+"&"+sendMsg, webSocket);
            log.info("成功发送AI消息");
            // 等待服务端返回完毕后关闭
        } catch (Exception e) {
            log.error("发送AI消息失败", e);
            webSocket.close(1000, "");
        }
    }
}
